﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace LocalLisaTestGUI
{
    /// <summary>
    /// This class is a UDP client. It is the basis for the EnvironmentEventSender and the UserCommandSender
    /// used to test and debug Lisa.
    /// 
    /// Thanks to: http://www.mastercsharp.com/article.aspx?ArticleID=66&&TopicID=14 for the UDP Code.
    /// </summary>
    class UDPClient
    {
        private UdpClient client;
        private IPEndPoint receivePoint;
        private int receivePort;   //Port on which Client can receive messages
        private int receiveIp;     //IP Address on which Client can receive messages (IP of client)
        private int sendPort;      //Port to which to send messages
        private int sendIp;        //The IP to which to send messages

        public UDPClient(int receiveIp, int receivePort, int sendIp, int sendPort)
        {
            this.receiveIp = receiveIp;
            this.receivePort = receivePort;
            this.sendIp = sendIp;
            this.sendPort = sendPort;
            //Create the UdpClient
            client = new UdpClient(receivePort);
            receivePoint = new IPEndPoint(new IPAddress(receiveIp), receivePort);
        }

        public void stop()
        {
            client.Close();
        }

        public void sendData(String data)
        {
            //Send DataGram
            //Format: Hostname@Post@Message
            System.Text.ASCIIEncoding encode = new System.Text.ASCIIEncoding();
            string sendString = "localhost@" + receivePort.ToString() + "@"+data;
            byte[] sendData = encode.GetBytes(sendString);
            //Send to Server 
            client.Send(sendData, sendData.Length, "localhost", sendPort);
        }
    }
}
